var fs = require('fs');
var request = require('request'); //请求网页
var cheerio = require('cheerio'); //分析dom结构
var mkdirp = require('mkdirp');
var async = require('async');
//目标网址
var url = 'http://www.runoob.com/';
//本地存储目录
var dir = './images';
//图片链接地址
var links = [];
//创建目录
mkdirp(dir, function (err) {
    if (err) {
        console.log(err);
    }
})
var lists = new Array();
request(url, function (err, res, body) {
    if (!err && res.statusCode == 200) {
        var $ = cheerio.load(res.body.toString());
        $(".codelist").eq(0).children("a").each(function () {
            var listImgUrl = $(this).find("img").attr("src");
            links.push(listImgUrl)
        })
        
        async.mapSeries(links, function (item, callback) {
            let base64 = item.replace(/^data:image\/\w+;base64,/, ""); //去掉图片base64码前面部分data:image/png;base64
            let dataBuffer = new Buffer(base64, 'base64'); //把base64码转成buffer对象，
            //download(item, dir, Math.floor(Math.random() * 100000) + item.substr(-4, 4));
            fs.writeFile('./images/'+Math.floor(Math.random() * 100000) + item.substr(-4, 4)+'.jpg',dataBuffer,function(err){
                if(err){
                    console.log(err);
                }else{
                    console.log('写入成功！');
                }
            })
            callback(null, item)

        }, function (err, results) {});
    }

});
// 主要方法，用于下载文件
var download = function (url, dir, filename) {
    request.head(url, function (err, res, body) {
        request(url).pipe(fs.createWriteStream(dir + "/" + filename));
    });
};